package com.woniuxy.controller;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.dto.ResidentsExcel;
import com.woniuxy.entity.Residents;
import com.woniuxy.mapper.ResidentsMapper;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/residentsExcel")
public class ResidentsExcelController {
    @Resource
    private ResidentsMapper residentsMapper;
    @PostMapping("/uploadResidents/{pageNum}/{pageSize}")
    public void exportResidents(@PathVariable("pageNum")Integer pageNum, @PathVariable("pageSize") Integer pageSize, HttpServletResponse  response) throws IOException {
        PageHelper.startPage(pageNum,pageSize);
        List<Residents> residents = residentsMapper.queryAllShow();
        PageInfo<Residents> residentsPageInfo = new PageInfo<>(residents);
        List<Residents> list = residentsPageInfo.getList();
        List<ResidentsExcel> listExcel = new ArrayList<>();
        for (Residents residents1 : list) {
            listExcel.add(new ResidentsExcel(residents1.getResidentId(),residents1.getName(),residents1.getPhoneNumber(),residents1.getIdCard(),residents1.getDiseasesString()));
        }
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        // 这里URLEncoder.encode可以防止中文乱码
        String fileName = URLEncoder.encode("居民信息.xlsx", String.valueOf(StandardCharsets.UTF_8));
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

        // 使用EasyExcel写入数据到输出流
        EasyExcel.write(response.getOutputStream(), ResidentsExcel.class)
                .sheet("居民列表")
                .doWrite(listExcel);
    }
}
